package biz.yfsoft.app.fastframework.api;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbPro;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

/**
 * 用于操作用户信息
 * @author James
 *
 */
@ClearInterceptor
public class OrderController extends Controller{
	
	public DbPro db = Db.use("biz"); 
	
	public DbPro ecDb = Db.use("ec");
	
	/**
	 * 创建订单
	 * @param login_name login_pass cfg_pass
	 * @author james 2016-03-02
	 */
	@Before(Tx.class)
	public void createOrder(){
		
		//订单类型 1:普通订单 5:预售订单 8:营销订单 11:退货订单 12:换货订单 13：第三方订单（百度，美团，饿了么）
		String type = getPara("type");
		String toName = getPara("toName");			 //收货人
		String toPhone = getPara("toPhone");		 //联系电话
		String toStreet = getPara("toStreet");		 //收货地址
		String total = getPara("total");			 //订单总金额
		String remark = getPara("remark");			 //订单备注
		String areaName = getPara("areaName");	     //区域
		String shopName = getPara("shopName");		 //果饮店
		String uid = getPara("uid");				 //下单人编号
		String couponId = getPara("couponId");		 //使用优惠券编号
		
		
		try {
			toName = new String(toName.getBytes("ISO-8859-1"));
			toPhone = new String(toPhone.getBytes("ISO-8859-1"));
			toStreet = new String(toStreet.getBytes("ISO-8859-1"));
			remark = new String(remark.getBytes("ISO-8859-1"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		
		
		
		String payway = "货到付款";					 //支付方式 默认"货到付款"
		String groupNo = "G";						 //订单组编号 以"G"开关
		String orderid = "O";						 //订单编号 以"O"开关
		String sql = "";
		int givePoint = 0;
		String strgoods = "";
		
		//订单状态 2000:已付款 2500:已审核 3000:已打票 7000:已打包 8000:已发货 9000:已收货 9999：已评价
		String status = "2000";
		

		Map<String,Object> o = new HashMap<String,Object>();
		
		o.put("errno", 0);
		o.put("code", "normal");
		o.put("msg", "运行正常");
		
		if(StringUtils.isEmpty(type)){
			o.put("errno", -701);
			o.put("code", "TYPE CANT BE EMPTY");
			o.put("msg", "订单类型不能为空");
		}else if(!"1".equals(type) && !"2".equals(type) && !"3".equals(type) && !"4".equals(type) && !"5".equals(type) && !"6".equals(type) && !"7".equals(type) && !"8".equals(type) && !"9".equals(type) && !"10".equals(type) && !"11".equals(type) && !"12".equals(type) && !"13".equals(type)){
			o.put("errno", -702);
			o.put("code", "TYPE ABNORMAL VALUE");
			o.put("msg", "订单类型值异常");
		}else if(StringUtils.isEmpty(toName)){
			o.put("errno", -703);
			o.put("code", "TONAME CANT BE EMPTY");
			o.put("msg", "收货人姓名不能为空");
		}else if(StringUtils.isEmpty(toPhone)){
			o.put("errno", -704);
			o.put("code", "TOPHONE CANT BE EMPTY");
			o.put("msg", "收货人联系电话不能为空");
		}else if(StringUtils.isEmpty(toStreet)){
			o.put("errno", -705);
			o.put("code", "TOSTREET CANT BE EMPTY");
			o.put("msg", "收货地址不能为空");
		}else if(StringUtils.isEmpty(total)){
			o.put("errno", -706);
			o.put("code", "TOTAL CANT BE EMPTY");
			o.put("msg", "订单金额不能为空");
		}else if(StringUtils.isEmpty(uid)){
			o.put("errno", -707);
			o.put("code", "UID CANT BE EMPTY");
			o.put("msg", "用户编号不能为空");
		}else if("8".equals(type) && StringUtils.isEmpty(areaName)){
			o.put("errno", -710);
			o.put("code", "AREANAME CANT BE EMPTY");
			o.put("msg", "区域不能为空");
		}else if("8".equals(type) &&StringUtils.isEmpty(shopName)){
			o.put("errno", -711);
			o.put("code", "SHOPNAME CANT BE EMPTY");
			o.put("msg", "果饮店不能为空");
		}else if("8".equals(type) && StringUtils.isEmpty(areaName) && !"A1".equals(areaName) && !"A2".equals(areaName) && !"A3".equals(areaName) && !"B1".equals(areaName) && !"B2".equals(areaName) && !"W1".equals(areaName) && !"W2".equals(areaName) && !"W3".equals(areaName)){
			o.put("errno", -712);
			o.put("code", "AREANAME ABNORMAL VALUE");
			o.put("msg", "区域值异常");
		}else if("8".equals(type) &&StringUtils.isEmpty(shopName) && !"果然总部".equals(shopName) && !"京华城店".equals(shopName) && !"虹桥坊店".equals(shopName) && !"梅岭店".equals(shopName) && !"望月店".equals(shopName) && !"时代店".equals(shopName) && !"三盛店".equals(shopName)){
			o.put("errno", -713);
			o.put("code", "SHOPNAME ABNORMAL VALUE");
			o.put("msg", "果饮店值异常");
		}else{
			
			if("8".equals(type)){
				//快递员下的营销订单
				/**
				 * 代码业务逻辑
				 * 1:根据uid到快递员的购物车内看是否有商品，y:继续 n:跳出（gr_api.lg_courier_cart）
				 * 2:根据购物车内商品编号获得商品完整数据（ecguoran100.gr_product,ecguoran100.gr_product_spec）
				 * 3:把信息插入到订单商品表（ecguoran100.gr_final_order_goods）
				 * 4:把信息插入到订单表（ecguoran100.gr_final_order）
				 * 5:把信息插入到订单组表（ecguoran100.gr_final_order_group）
				 * 6:把信息插入到订单物流信息表（gr_api.lg_mission）
				 * 7:删除该用户的购物车商品（gr_api.lg_courier_cart）
				 */
				
				String sjc = Long.toString(System.currentTimeMillis());
				orderid = "Y"+sjc;
				groupNo = "G"+sjc;
				
				int t = 0;
				
				//1:根据uid到快递员的购物车内看是否有商品，y:继续 n:跳出（gr_api.lg_courier_cart）
				List<Record> courier_cart = db.find("select pid,psid,number from lg_courier_cart a where a.status = 1 and a.number > 0 and a.uid = ?",uid);
				if(courier_cart.size() == 0){
					o.put("errno", -708);
					o.put("code", "There is no data in the shopping cart");
					o.put("msg", "该用户的购物车内没有数据");
				}else{
					
					for(int i=0;i<courier_cart.size();i++){
						//判断商品是否下架
						int psid = Integer.parseInt(courier_cart.get(i).getStr("psid"));			//规格编号
						List<Record> spec = ecDb.find("select 1 from gr_product a,gr_product_spec b where a.id = b.pid and a.status = 1 and b.status = 1 and b.id = ?",psid);
						if(spec.size() == 0){
							t = 1;
						}
					}
					
					if(t==0){
						for(int i=0;i<courier_cart.size();i++){
							//2:根据购物车内商品编号获得商品完整数据（ecguoran100.gr_product,ecguoran100.gr_product_spec）
							int pid = Integer.parseInt(courier_cart.get(i).getStr("pid"));			//商品编号
							int psid = Integer.parseInt(courier_cart.get(i).getStr("psid"));			//规格编号
							int number = courier_cart.get(i).getInt("number");		//购买件数
							
							List<Record> product = ecDb.find("select name from gr_product a where a.status = 1 and a.id = ?",pid);
							List<Record> product_spec = ecDb.find("select name,point,packageprice from gr_product_spec a where a.status = 1 and a.id = ?",psid);
							
							String proname = product.get(0).getStr("name");							//商品名称
							String spname = product_spec.get(0).getStr("name");						//规格名称
							int point = product_spec.get(0).getInt("point");		//商品积分
							double price = product_spec.get(0).getDouble("packageprice");//商品价格
							double totalprice = price * number;									   //总价  商品价格 * 购买件数
							
							strgoods += proname+"("+spname+")/"+totalprice+"元"+number+"份;";					//商品信息
							givePoint += point * number;														//赠送积分
							
							//3:把信息插入到订单商品表（ecguoran100.gr_final_order_goods）
							Record goods = new Record();
							goods.set("orderid", orderid);
							goods.set("pid", pid);
							goods.set("specid", psid);
							goods.set("price", price);
							goods.set("cartnum", number);
							goods.set("point", point);
							goods.set("totalprice", totalprice);
							goods.set("proname", proname);
							goods.set("spname", spname);
							goods.set("createAt", sjc.substring(0,10));
							goods.set("updateAt", sjc.substring(0,10));
							ecDb.save("gr_final_order_goods", goods);
						}
						
						//4:把信息插入到订单表（ecguoran100.gr_final_order）
						Record order = new Record();
						order.set("orderid", orderid);
						order.set("groupNo", groupNo);
						order.set("type", type);
						order.set("amount", total);
						order.set("finalAmount", total);
						order.set("payway", payway);
						order.set("payDetails", payway+":"+total+"元");
						order.set("payTime", sjc.substring(0,10));
						
						int areaId = 0;
						int shopId = 0;
						
						if("A1".equals(areaName)){
							areaId = 63;
						}else if("A2".equals(areaName)){
							areaId = 66;
						}else if("A3".equals(areaName)){
							areaId = 64;
						}else if("B1".equals(areaName)){
							areaId = 65;
						}else if("B2".equals(areaName)){
							areaId = 67;
						}else if("W1".equals(areaName)){
							areaId = 46;
						}else if("W2".equals(areaName)){
							areaId = 43;
						}else if("W3".equals(areaName)){
							areaId = 44;
						}
						
							
						if("果然总部".equals(shopName)){
							shopId = 1;
						}else if("京华城店".equals(shopName)){
							shopId = 2;
						}else if("虹桥坊店".equals(shopName)){
							shopId = 3;
						}else if("梅岭店".equals(shopName)){
							shopId = 4;
						}else if("望月店".equals(shopName)){
							shopId = 5;
						}else if("时代店".equals(shopName)){
							shopId = 6;
						}else if("三盛店".equals(shopName)){
							shopId = 7;
						}
							
						order.set("areaId", areaId);
						order.set("shopId", shopId);
						order.set("status", 2500);
						order.set("goods", strgoods);
						order.set("givePoint", givePoint);
						order.set("approvaluid", 1);
						order.set("approvaldate", sjc.substring(0,10));
						order.set("bookdate", sjc.substring(0,10));
						order.set("createAt", sjc.substring(0,10));
						order.set("updateAt", sjc.substring(0,10));
						ecDb.save("gr_final_order", order);
						
						//5:把信息插入到订单组表（ecguoran100.gr_final_order_group）
						Record ordergroup = new Record();
						ordergroup.set("groupNo", groupNo);
						ordergroup.set("uid", uid);
						ordergroup.set("toName", toName);
						ordergroup.set("toPhone", toPhone);
						ordergroup.set("toStreet", toStreet);
						ordergroup.set("remark", remark);
						ordergroup.set("couponId", couponId);
						ordergroup.set("toLon", "0");
						ordergroup.set("toLat", "0");
						ordergroup.set("pLng", "0");
						ordergroup.set("pLat", "0");
						ordergroup.set("confidence", "100");
						ordergroup.set("coordinateId", "0");
						ordergroup.set("createAt", sjc.substring(0,10));
						ordergroup.set("updateAt", sjc.substring(0,10));
						ecDb.save("gr_final_order_group", ordergroup);
						
						//6:把信息插入到订单物流信息表（gr_api.lg_mission）
						Record mission = new Record();
						mission.set("from_name", "果然100");
						mission.set("from_tel", "4009288898");
						mission.set("from_address", "江苏扬州");
						mission.set("to_name", toName);
						mission.set("to_tel", toPhone);
						mission.set("to_address", toStreet);
						mission.set("code", orderid);
						mission.set("pay_way", payway);
						mission.set("final_amount", total);
						mission.set("area_name", couponId);
						mission.set("src_remark", remark);
						mission.set("src_code", orderid);
						mission.set("src_sys", "GR100");
						mission.set("status", status);
						mission.set("type", type);
						mission.set("marketing_uid", uid);
						mission.set("marketing_rebate", 0);
						mission.set("express_rebate", 0);
						mission.set("createAt", sjc.substring(0,10));
						mission.set("updateAt", sjc.substring(0,10));
						db.save("lg_mission", mission);
						
						//7:删除该用户的购物车商品（gr_api.lg_courier_cart）
						Record cart = new Record();
						cart.set("uid", uid);
						db.deleteById("lg_courier_cart", "uid", uid);
						
						Map<String,Object> p = new HashMap<String,Object>();
						p.put("groupNo", groupNo);
						p.put("orderid", orderid);
						p.put("total", total);
						p.put("point", givePoint);
						o.put("data", p);
					}else{
						o.put("errno", -709);
						o.put("code", "The goods have been off the shelf");
						o.put("msg", "创建订单失败，系统检测部分商品已下架");
					}
				}
			}
		}
		renderJson(o);
	}
}
